package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.FlowModelVariableService;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowModelVariableVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowModelVariableRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: liyang
 * @date: 2021/11/30 16:15
 */
@Service
public class FlowModelVariableServiceImpl implements FlowModelVariableService {

    @Autowired
    private FlowModelVariableRepository flowModelVariableRepository;

    @Override
    public Map<String, Object> setDefaultValueToVariables(String deploymentId, Map<String, Object> variables) {
        if (Objects.isNull(variables)){
            variables = new HashMap<>();
        }
        List<FlowModelVariableVo> flowModelVariableVoList = flowModelVariableRepository.getModelVariables(deploymentId);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(flowModelVariableVoList)){
            for (FlowModelVariableVo flowModelVariableVo : flowModelVariableVoList) {
                if (variables.containsKey(flowModelVariableVo.getCode())){
                    continue;
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(flowModelVariableVo.getDefaultValue())){
                    if (isAssigneeType(flowModelVariableVo)) {
                        JSONObject object = JSONObject.parseObject(flowModelVariableVo.getDefaultValue());
                        Object value = object.get("value");
                        variables.put(flowModelVariableVo.getCode(), value);
                    } else {
                        variables.put(flowModelVariableVo.getCode(), flowModelVariableVo.getDefaultValue());
                    }
                }
            }
        }
        return variables;
    }

}
